package jwt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const (
	TokenExp = time.Hour * 30
	Secret   = "423$@#345#$%!@#FGSDG23"
)

type XClaims struct {
	UserID   uint64 `json:"userID"`
	Username string `json:"username"`
	jwt.StandardClaims
}

// 生成 token
func GenToken(uid uint64, uname string) (string, error) {
	c := XClaims{
		UserID:   uid,
		Username: uname,
	}

	c.ExpiresAt = time.Now().Add(TokenExp).Unix()
	c.Issuer = "go-web-app-demo"

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)

	return token.SignedString([]byte(Secret))
}

func ParseToken(t string) (*XClaims, error) {

	xc := new(XClaims)
	token, err := jwt.ParseWithClaims(t, xc, func(token *jwt.Token) (interface{}, error) {
		return Secret, nil
	})

	if err != nil {
		return nil, err
	}
	if token.Valid {
		return xc, err
	}

	return nil, errors.New("invalid token")
}
